package com.zs.leymovie.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.zs.leymovie.R;
import com.zs.leymovie.adapter.GalleryImgAdapter;
import com.zs.leymovie.adapter.RecyAdapter;
import com.zs.leymovie.adapter.YyItemPtrAdapter;
import com.zs.leymovie.bean.CinemaDataEntity;
import com.zs.leymovie.bean.EveryDay;
import com.zs.leymovie.bean.YyMoveSummry;
import com.zs.leymovie.constants.UrlConstants;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 显示 第个电影院的 相关信息
 */
public class YyItemActivity extends AppCompatActivity  implements PullToRefreshBase.OnRefreshListener2, AdapterView.OnItemClickListener {
    @ViewInject(R.id.yyitem_ptrlistview)
    private PullToRefreshListView ptrListView;
    private CinemaDataEntity entity;
    private boolean flag = true;    //收藏标志
    private YyItemPtrAdapter ptrAdapter ;
    private List<EveryDay> lists = new ArrayList<>();
    private HttpUtils httpUtils;
    private HttpHandler handler;
    private String today="";
    private HashMap<String ,List<EveryDay>> map = new HashMap<>();   //"2015-08-20": [{电影对象1},{电影对象1}]
    private List<YyMoveSummry> moveList = new ArrayList<>();
    private String city_id = "";
    private  HeadView headView;
    private   RecyAdapter adapter;
    private HashMap<Integer,ArrayList<String>> alldy = new HashMap<>();
    private int dayclick =0;
    private int moveClick = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yy_item);

        entity = (CinemaDataEntity) getIntent().getExtras().getSerializable("cimeadata");
        city_id = getIntent().getStringExtra("cityid");
        ViewUtils.inject(this);
        initView();
        initData();
    }

    private void initData() {
        httpUtils = new HttpUtils();
        handler = httpUtils.send(HttpRequest.HttpMethod.GET, UrlConstants.getMoveData(city_id, entity.getId()), new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                  String result = responseInfo.result;
                  parseData(result);
                 headView.initSubData();   //数据解析完初始化头部文件的数据
            }

            @Override
            public void onFailure(HttpException e, String s) {
                ptrListView.onRefreshComplete();
                Toast.makeText(YyItemActivity.this,"数据加载失败，请稍候再试",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void parseData(String result){
        try {
            JSONObject object = new JSONObject(result);
            int status =  object.getInt("status");
            if(status == 1){    //成功
                JSONObject  obj = object.getJSONObject("data");
                today = obj.getString("today");
                JSONArray array = obj.getJSONArray("movie_data");      //得到movie_data字段的数组对象
                for (int i = 0; i < array.length(); i++) {
                    JSONObject obj1 = array.getJSONObject(i);  //取出每部电影的对象
                    String id =obj1.getString("movie_id");
                    String name = obj1.getString("movie_name");
                    String desc = obj1.getString("movie_desc");
                    String score = obj1.getString("movie_score");
                    String isnew = obj1.getString("is_new");
                    String sort = obj1.getString("sort");
                    String url = obj1.getString("movie_img_url");
                    String isonline = obj1.getString("is_online");
                    JSONArray days = obj1.getJSONArray("days");    //最近的天数
                    JSONObject onedayall = obj1.getJSONObject("shows");  //每天的放映
                    // String shows = obj1.getString("shows");
                    // ShowMoveData showMoveData = com.alibaba.fastjson.JSONObject.parseObject(shows,ShowMoveData.class); //得到具体一天的所有放映信息
                    ArrayList<String> arrdays = new ArrayList<>();
                    for (int j = 0; j < days.length(); j++) {
                        arrdays.add((String)days.get(j));      //把所有的天数数组转换成集合
                    }
                    alldy.put(i,arrdays);   //加入该影院播放的天数
                    HashMap<String,List<EveryDay>> hashMaps = new HashMap<>();

                    for (int j = 0; j < days.length(); j++) {
                        JSONArray dayarray = onedayall.getJSONArray(days.getString(j));    //得到指定key日期的对象，这里是j
                        List<EveryDay> everyDays = new ArrayList<>();

                        for (int k = 5; k < dayarray.length(); k++) {
                            EveryDay everyDay = new EveryDay();
                            JSONObject obj4 = dayarray.getJSONObject(k);    //得到具体某一天的所有放映的电影信息
                            everyDay.setShow_id((obj4.getString("show_id")));
                            everyDay.setStart_time(obj4.getString("start_time"));
                            everyDay.setEnd_time((obj4.getString("end_time")));
                            everyDay.setLanguage((obj4.getString("language")));
                            everyDay.setMedia((obj4.getString("media")));
                            everyDay.setPrice((obj4.getString("price")));
                            everyDay.setHall_name((obj4.getString("hall_name")));
                            everyDay.setOrigi_price((obj4.getString("origi_price")));
                            everyDays.add(everyDay);   //把每天的电影对象放入到电影集合
                           // Log.e("----everyday",""+everyDay);
                        }
                        hashMaps.put(days.getString(j),everyDays);   //把时间作为键，当天所有的电影作为值,这里是j
                    }
                    YyMoveSummry summry = new YyMoveSummry(id,name,desc,score,isnew,sort,url,isonline,alldy,hashMaps);
                    moveList.add(summry);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }



    private void initView() {
        ptrListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        ListView listview = ptrListView.getRefreshableView();
       // LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View hView = LayoutInflater.from(this).inflate(R.layout.yyptr_headview,null);
        headView = new HeadView(hView);
        listview.addHeaderView(hView);

        ptrAdapter = new YyItemPtrAdapter(lists,this,city_id);
        ptrListView.setOnRefreshListener(this);  //设置trlistview的监听
        ptrListView.setAdapter(ptrAdapter);    //设置ptrlistview的适配器
        ptrListView.setOnItemClickListener(this);  //设置item的点击监听
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {

    }

    //ptrlistview的item的点击监听
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = new Intent(this,XuanZuoActivity.class);
        String start_time = lists.get(position-2).getStart_time();  //这里需要把减去2
        String show_id = lists.get(position-2).getShow_id();
        intent.putExtra(UrlConstants.SHOW_ID,show_id);
        intent.putExtra(UrlConstants.CITY_ID,city_id);
        startActivity(intent);
    }


    public class HeadView implements AdapterView.OnItemClickListener, RecyAdapter.RecyViewOnClickListener, AdapterView.OnItemSelectedListener {
        @ViewInject(R.id.yy_item_title)
        private TextView  barname;
        @ViewInject(R.id.yy_item_shoucang)
        private ImageView right_sc_btn;
        @ViewInject(R.id.yy_item_back)
        private ImageView left_back_btn;
        @ViewInject(R.id.yyitem_gallery)
        private Gallery gallery;
        private GalleryImgAdapter imgAdapter;
        @ViewInject(R.id.yyitem_above_title)
        private TextView cimaname;
        @ViewInject(R.id.yyitem_above_addr)
        private TextView cimaaddr;
        @ViewInject(R.id.yyitem_movename)
        private TextView moveName;          //电影名
        @ViewInject(R.id.yyitem_score)
        private TextView moveScore;         //评分
        @ViewInject(R.id.yyitem_movedetail)
        private TextView movedetail; //详情
        @ViewInject(R.id.yyitem_godetal_btn)
        private ImageView img_godetail;     //去往详情界面
        private List<String> imgUrlList = new ArrayList<>();
        @ViewInject(R.id.yyitem_recyview)
        private RecyclerView recyView;
        private List<String>recyList = new ArrayList<>();
        public  HashMap<String, List<EveryDay>> currentdays;
        private HttpHandler handler2;
        public  HashMap<Integer, ArrayList<String>> tempall;
        @ViewInject(R.id.yyitem_err_image)
        private TextView errText ;
        public HeadView(View view){
            ViewUtils.inject(this,view);
            initHeadView();
        }


        private void initHeadView() {
            barname.setText(entity.getName());   //设置actionbar显示的名字
            cimaname.setText(entity.getName());   //图片上显示的名字
            cimaaddr.setText(entity.getAddress());  //图片上显示的地址

            imgAdapter = new GalleryImgAdapter(imgUrlList,YyItemActivity.this);
            gallery.setAdapter(imgAdapter);
            gallery.setOnItemClickListener(this);
            gallery.setOnItemSelectedListener(this);

            LinearLayoutManager manager = new LinearLayoutManager(YyItemActivity.this);
            manager.setOrientation(LinearLayoutManager.HORIZONTAL);  //水平方向
            adapter  = new RecyAdapter(recyList,YyItemActivity.this);
            adapter.setOnRecyViewOnClickListener(this);   //实现监听的方法
            recyView.setLayoutManager(manager);
            recyView.setAdapter(adapter);

        }

        public void initSubData(){
            moveName.setText(moveList.get(moveClick).getMovie_name());
            moveScore.setText(moveList.get(moveClick).getMovie_score()+"分");
            movedetail.setText(moveList.get(moveClick).getMovie_desc());

            if(imgUrlList.size() == 0 && moveList.size()>=5){   //只添加5张图片，且只有第一次添加
                for (int i = 0; i < moveList.size(); i++) {
                    imgUrlList.add(moveList.get(i).getMovie_img_url());   //添加图片的地址
                }
                imgAdapter.notifyDataSetChanged();
            }

            /**
             * 切换日期
             */
           /*  tempall = moveList.get(moveClick).getAlldy();
            ArrayList<String>  temponedayall = tempall.get(dayclick);*/
            if(recyList!=null){
                recyList.clear();
            }
            recyList.addAll(alldy.get(moveClick));  //得到天数
            adapter.notifyDataSetChanged();
            /**
             *  改变list的数据
             */
            currentdays = moveList.get(moveClick).getHashMaps();  //得到第一部电影

            List<EveryDay> ev=  currentdays.get(recyList.get(dayclick));   //得到某一天的所有电影
            if(lists!=null && lists.size()>0){
                lists.clear();
            }
            lists.addAll(ev);
            ptrAdapter.notifyDataSetChanged();
        }

        @OnClick({R.id.yy_item_shoucang,R.id.yy_item_back,R.id.yyitem_godetal_btn,R.id.yyitem_movedetail})
        public void onClick(View view){
            switch (view.getId()){
                case R.id.yy_item_shoucang:   //收藏
                    if(flag){
                        right_sc_btn.setImageResource(R.mipmap.changci_icon_shoucangxuanzhong);
                        Toast.makeText(YyItemActivity.this,"收藏成功",Toast.LENGTH_LONG).show();
                        flag = false;
                    }else{
                        right_sc_btn.setImageResource(R.mipmap.changci_icon_shoucang);
                        Toast.makeText(YyItemActivity.this,"取消成功",Toast.LENGTH_LONG).show();
                        flag = true;
                    }
                    break;
                case R.id.yy_item_back:    //返回
                    YyItemActivity.this.finish();
                    break;
                case R.id.yyitem_movedetail:
                case R.id.yyitem_godetal_btn:   //去往详情
                    Intent intent = new Intent();
                    intent.setClass(YyItemActivity.this,MovieDetailActivity.class);
                    intent.putExtra("flag","yyMoving");  //标志是否已经上映
                   // intent.putExtra("is_online",moveList.get(moveClick).getIs_online());
                    intent.putExtra("moveName",moveList.get(moveClick).getMovie_name());   //电影名
                    intent.putExtra("moveId",moveList.get(moveClick).getMovie_id());  //电影ID
                    intent.putExtra("cityId",city_id);  //城市ID
                    startActivity(intent);
                    break;
            }
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            moveClick = position;
            dayclick = 0;
            initSubData();
        }

        /**
         * 日期的点击事件
         * @param v
         * @param position
         */
        @Override
        public void recyViewItemClick(View v, int position) {
            dayclick = position;
            currentdays = moveList.get(moveClick).getHashMaps();  //得到第一部电影
            List<EveryDay> ev=  currentdays.get(recyList.get(dayclick));   //得到某一天的所有电影
            if(lists!=null && lists.size()>0){
                lists.clear();
                errText.setVisibility(View.GONE);
            }else{
               // Toast.makeText(YyItemActivity.this,"今天没有数据",Toast.LENGTH_SHORT).show();
                errText.setVisibility(View.VISIBLE);
            }
            lists.addAll(ev);
            ptrAdapter.notifyDataSetChanged();
        }

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            imgAdapter.setSelectItem(position);
            imgAdapter.notifyDataSetChanged();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    }

    //释放资源
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(handler !=null && !handler.isCancelled()){
            handler.cancel();
        }
    }

    //暂停下载
    @Override
    protected void onPause() {
        super.onPause();
        if(handler !=null && !handler.isPaused()){
            handler.pause();
        }
    }
}
